package com.study.selenium.page.google;


import com.study.selenium.annotation.PageFragment;
import com.study.selenium.page.Base;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

@PageFragment// using custom annotation created; src/main/java/com/demo/seleniumspring/annotation/PageFragment.java
public class SearchComponent extends Base {

//    @FindBy(name = "q")
//    private WebElement searchBox;
//
//    @FindBy(name = "btnK")
//    private List<WebElement> searchButtonList;

    public void search(final String keyword) {
//        this.searchBox.sendKeys(keyword);
//        this.searchBox.sendKeys(Keys.TAB);
//        // CLICK first search button
//        this.searchButtonList.stream()
//                .filter(e -> e.isDisplayed() && e.isEnabled())
//                .findFirst()
//                .ifPresent(WebElement::click);

        WebElement searchButton = driver.findElement(By.id("kw"));
        searchButton.sendKeys(keyword);
        searchButton.sendKeys(Keys.ENTER);

        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(4));

        jumpNextPage();

        WebElement element = driver.findElement(By.id("wrapper_wrapper"));
        System.out.println(element);

        WebElement article = driver.findElement(By.className("c-container"));
        System.out.println(article);
        WebElement a1 = article.findElement(By.tagName("a"));
        System.out.println(a1.getText());
        a1.click();

        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(4));
        // 获取当前打开窗口的句柄
        String originalWindow = driver.getWindowHandle();
        // 循环遍历所有打开的窗口，切换到新窗口
        for (String handle : driver.getWindowHandles()) {
            if (!handle.equals(originalWindow)) {
                driver.switchTo().window(handle);
                // 在新窗口执行操作
                System.out.println("Switched to new window: " + driver.getTitle());
                // 关闭新窗口
                //driver.close();
            }
        }
        // 切换回原始窗口
        //driver.switchTo().window(originalWindow);
    }

    private void jumpNextPage(){
        // 获取当前打开的页面的句柄
        String newWindowHandle = driver.getWindowHandles().iterator().next();
        // 切换到新页面
        driver.switchTo().window(newWindowHandle);
    }

    @Override
    public boolean isAt() {
        return this.wait.until(driver1 -> {
            System.out.println("driver1="+driver1);
//            boolean bool =  this.searchBox.isDisplayed();
//            System.out.println("bool="+bool);
            return true;
        });
    }
}
